package com.yupi.goj.judge;

import cn.hutool.json.JSONUtil;
import com.yupi.goj.common.ErrorCode;
import com.yupi.goj.exception.BusinessException;
import com.yupi.goj.judge.codesandbox.CodeSandbox;
import com.yupi.goj.judge.codesandbox.CodeSandboxFactory;
import com.yupi.goj.judge.codesandbox.model.ExecuteCodeRequest;
import com.yupi.goj.judge.codesandbox.model.ExecuteCodeResponse;
import com.yupi.goj.judge.strategy.JudgeContext;
import com.yupi.goj.model.dto.question.JudgeCase;
import com.yupi.goj.judge.codesandbox.model.JudgeInfo;
import com.yupi.goj.model.entity.Question;
import com.yupi.goj.model.entity.QuestionSubmit;
import com.yupi.goj.model.enums.JudgeInfoMessageEnum;
import com.yupi.goj.model.enums.QuestionSubmitStatusEnum;
import com.yupi.goj.service.QuestionService;
import com.yupi.goj.service.QuestionSubmitService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class JudgeServiceImpl implements JudgeService {

    @Resource
    private QuestionService questionService;

    @Resource
    private QuestionSubmitService questionSubmitService;

    @Value("${codesandbox.type:example}")
    private String type;

    @Resource
    private JudgeManager judgeManager;

    @Override
    public QuestionSubmit doJudge(long questionSubmitId) {
        // 1) 传入题目的提交 id，获取到对应的题目、提交信息（包含代码、编程语言等）
        QuestionSubmit questionSubmit = questionSubmitService.getById(questionSubmitId);
        if (questionSubmit == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "提交信息不存在");
        }
        Long questionId = questionSubmit.getQuestionId();
        Question question = questionService.getById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "题目不存在");
        }

        // 2) 如果不为等待中
        if (!questionSubmit.getStatus().equals(QuestionSubmitStatusEnum.WAITING.getValue())) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "题目正在判题中");
        }
        // 3) 更改判题（题目提交）的状态为 "判题中"，防止重复执行
        QuestionSubmit questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());
        boolean update = questionSubmitService.updateById(questionSubmitUpdate);
        if (!update) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目状态更新错误");
        }
        // 4) 调用代码沙箱，获取到执行结果
        CodeSandbox codeSandBox = CodeSandboxFactory.newInstance(type);
        String judgeCaseStr = question.getJudgeCase();
        List<JudgeCase> judgeCaseList = JSONUtil.toList(judgeCaseStr, JudgeCase.class);
        String language = questionSubmit.getLanguage();
        String code = questionSubmit.getCode();
        List<String> inputList = judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());
        ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest.builder()
                .code(code)
                .inputList(inputList)
                .language(language)
                .build();
        ExecuteCodeResponse executeCodeResponse = codeSandBox.executeCode(executeCodeRequest);
        List<String> outputList = executeCodeResponse.getOutputList();
        // 5) 根据沙箱的执行结果，设置题目的判题状态和信息
        // 如果编译错误直接返回结果
        if (executeCodeResponse.getStatus() == 2 || executeCodeResponse.getStatus() == 3 || executeCodeResponse.getStatus() == 4) {
            questionSubmitUpdate = new QuestionSubmit();
            questionSubmitUpdate.setId(questionSubmitId);
            questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.FAILED.getValue());
            questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(executeCodeResponse.getJudgeInfo()));
            update = questionSubmitService.updateById(questionSubmitUpdate);
            if (!update) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目状态更新错误");
            }

            synchronized (this) {
                question = questionService.getById(questionId);
                Integer submitNum = question.getSubmitNum();
                question.setSubmitNum(submitNum + 1);
                update = questionService.updateById(question);
                if (!update) {
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目更新失败");
                }
            }

            QuestionSubmit questionSubmitResult = questionSubmitService.getById(questionSubmitId);
            return questionSubmitResult;
        }

        JudgeContext judgeContext = new JudgeContext();
        judgeContext.setJudgeInfo(executeCodeResponse.getJudgeInfo());
        judgeContext.setInputList(inputList);
        judgeContext.setOutputList(outputList);
        judgeContext.setJudgeCaseList(judgeCaseList);
        judgeContext.setQuestion(question);
        judgeContext.setQuestionSubmit(questionSubmit);
        JudgeInfo judgeInfo = judgeManager.doJudge(judgeContext);

        // 6) 修改数据库中的判题结果
        questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.SUCCESS.getValue());
        questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
        update = questionSubmitService.updateById(questionSubmitUpdate);
        if (!update) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目状态更新错误");
        }

        synchronized (this) {
            question = questionService.getById(questionId);
            Integer submitNum = question.getSubmitNum();
            Integer acceptedNum = question.getAcceptedNum();
            question.setSubmitNum(submitNum + 1);
            if (JudgeInfoMessageEnum.ACCEPTED.getValue().equals(judgeInfo.getMessage())) {
                question.setAcceptedNum(acceptedNum + 1);
            }
            update = questionService.updateById(question);
            if (!update) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目更新失败");
            }
        }

        QuestionSubmit questionSubmitResult = questionSubmitService.getById(questionSubmitId);

        return questionSubmitResult;
    }
}
